package aspectos;

import java.util.*;

import dominio.Persona;
import adicionales.Tupla;
import annotations.Monitored;
							
public aspect ContadorLlamadasAspect{
	
	private Map<Object,ArrayList<Tupla>> map = new HashMap<Object,ArrayList<Tupla>>();
	
	pointcut monitoringCatch(Object target):
	call(@Monitored * *(..))&& target(target);
	
	before(Object target):monitoringCatch(target){
		agregarConteoAlMap(target, thisJoinPoint.getSignature().getName());
	}
	
	public int cantLlamadas(Object p1, String st){
		if(map.containsKey(p1)){
			return this.searchFor(p1,st);
		}else{
			return 0;
		}
		
	}
	
	protected int searchFor(Object p1, String st) {
		ArrayList<Tupla> t = map.get(p1);
		for(int i = 0; i < t.size(); i++){
			Tupla tmp = t.get(i);
			if(t.get(i).getSourceMetodo().contains(st)){
				return tmp.getCantidadDeLlamadas();
			}
		}
		return 0;
	}
	
	protected void agregarConteoAlMap(Object target, String source) {
		if(this.map.containsKey(target)){
			ArrayList<Tupla> t = this.map.get(target);
			boolean sumo = false;
			for(int i = 0; i < t.size(); i++){
				if(t.get(i).getSourceMetodo().contains(source)&&!sumo){
					t.get(i).setCantidadDeLlamadas((t.get(i).getCantidadDeLlamadas() + 1));
					sumo = true;
				}
			}
			if(!sumo){
				t.add(new Tupla(source, 1));
			}
		}else{
			ArrayList<Tupla> lista = new ArrayList<Tupla>();
			lista.add(new Tupla(source,1));
			this.map.put(target, lista);
		}
	}

	
}
